package com.manopservice.controller;

import java.util.HashMap;
import java.util.Map;

import com.manopservice.model.CarModel;
import com.manopservice.service.CarBrandService;
import com.manopservice.service.CarModelService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/carModels")
public class CarModelController {

	@Autowired
	private CarModelService carModelService;
	
	@Autowired
	private CarBrandService carBrandService;
	
	@RequestMapping(value = "/ShowCarModels", method = RequestMethod.POST)
	public ModelAndView showCarPart() {
		
		return listCarModels();
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView saveCarModel(@ModelAttribute("carModel") CarModel  carModel, @RequestParam int carBrandId,
			BindingResult result) {
		carModel.setCarBrand(carBrandService.findCarBrandById(carBrandId));
		carModelService.addCarModel(carModel);
		return new ModelAndView("redirect:/carModels.html");
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public ModelAndView deleteModel(@ModelAttribute("carModel") CarModel  carModel,
			BindingResult result) {
		carModelService.deleteCarModel(carModel.getId());
		return new ModelAndView("redirect:/carModels.html");
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView listCarModels() {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("carModels",  carModelService.listCarModels());

		return new ModelAndView("carModelsList", model);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView addCarModel(@ModelAttribute("carModel") CarModel carModel,
			BindingResult result) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("carBrands",  carBrandService.listCarBrands());
		return new ModelAndView("addCarModel", model);
	}
	
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView editCarModel(@ModelAttribute("carModel") CarModel carModel,
			BindingResult result) {
		
		CarModel cm = carModelService.findCarModelById(carModel.getId());
		carModel.setNameThai(cm.getNameThai());
		carModel.setNameEng(cm.getNameEng());
		
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("carBrands",  carBrandService.listCarBrands());
		model.put("brandId",  carBrandService.findCarBrandById(cm.getCarBrand().getId()));
		return new ModelAndView("editCarModel", model);
	}

}